package Util;

import Pojo.AliPayConfig;
import Pojo.Pay;
import com.alipay.api.*;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.TradeFundBill;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.demo.trade.config.Configs;
import com.alipay.demo.trade.model.builder.AlipayTradePayRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradeQueryRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradeRefundRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPayResult;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.model.result.AlipayF2FQueryResult;
import com.alipay.demo.trade.model.result.AlipayF2FRefundResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import com.alipay.demo.trade.utils.Utils;
import org.junit.Test;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class AliPayUtil2 {
    private static AlipayTradeService alipayTradeService;
    //初始化SDK
    static {
//        AlipayClient alipayClient=new DefaultAlipayClient(
//                AliPayConfig.gatewayUrl,
//                AliPayConfig.app_id,
//                AliPayConfig.merchant_private_key,
//                "json",
//                AliPayConfig.charset,
//                AliPayConfig.alipay_public_key,
//                AliPayConfig.sign_type
//                );
        Configs.init("Config/zfbinfo.properties");
        alipayTradeService=new AlipayTradeServiceImpl.ClientBuilder().build();
    }
    //流程支付
    public AlipayF2FPayResult tradePay(AlipayTradePayRequestBuilder alipayTradePayRequestBuilder) {
        return null;
    }
    //消费查询
    public AlipayF2FQueryResult queryTradeResult(AlipayTradeQueryRequestBuilder alipayTradeQueryRequestBuilder) {
        return null;
    }
    //退款
    public AlipayF2FRefundResult tradeRefund(AlipayTradeRefundRequestBuilder alipayTradeRefundRequestBuilder) {
        return null;
    }
    //预下单(生成二维码)
    public static AlipayF2FPrecreateResult tradePrecreate(Pay pay) {
        AlipayTradePrecreateRequestBuilder at=new AlipayTradePrecreateRequestBuilder();
        at.setOutTradeNo(pay.getOut_trade_no());
        at.setSubject(pay.getSubject());
        at.setStoreId(pay.getStore_id());
        at.setTotalAmount(pay.getTotal_amount());
        at.setBody(pay.getBody());
        at.setNotifyUrl("http://g689b7aa.natappfree.cc/dhjourney/PaySnackStatusQueryServlet");//支付宝通知
        at.setTimeoutExpress(pay.getTimeout_express());
        return alipayTradeService.tradePrecreate(at);
    }
    //验签
    public static Map<String,String> convertRequestParamsToMap(HttpServletRequest request){
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }
        return retMap;
    }

    // 测试当面付2.0查询订单
    public static String TestTradeQuery(String out_trade_no) {
        String statusResult="";
        // (必填) 商户订单号，通过此商户订单号查询当面付的交易状态
        String outTradeNo = out_trade_no;

        // 创建查询请求builder，设置请求参数
        AlipayTradeQueryRequestBuilder builder = new AlipayTradeQueryRequestBuilder()
                .setOutTradeNo(outTradeNo);

        AlipayF2FQueryResult result = alipayTradeService.queryTradeResult(builder);
        switch (result.getTradeStatus()) {
            case SUCCESS:
                System.out.println("查询返回该订单支付成功: )");
                AlipayTradeQueryResponse response = result.getResponse();
                System.out.println(response.getTradeStatus());
                if (Utils.isListNotEmpty(response.getFundBillList())) {
                    for (TradeFundBill bill : response.getFundBillList()) {
                        System.out.println(bill.getFundChannel() + ":" + bill.getAmount());
                    }
                }
                statusResult="success";
                break;

            case FAILED:
                System.out.println("查询返回该订单支付失败或被关闭!!!");
                statusResult="fail";
                break;

            case UNKNOWN:
                System.out.println("系统异常，订单支付状态未知!!!");
                statusResult="error";
                break;
            default:
                System.out.println("不支持的交易状态，交易返回异常!!!");
                statusResult="error";
                break;
        }
        return statusResult;
    }


    @Test
    public void AliPayModelTest() throws AlipayApiException {
        //初始化sdk
        AlipayClient alipayClient=new DefaultAlipayClient(
                AliPayConfig.gatewayUrl,
                AliPayConfig.app_id,
                AliPayConfig.merchant_private_key,
                "json",
                AliPayConfig.charset,
                AliPayConfig.alipay_public_key,
                AliPayConfig.sign_type
        );
        //创建支付模型(简称假支付,没有沙箱的时候用它测试能不能买)
        AlipayTradePagePayModel model=new AlipayTradePagePayModel();
        model.setOutTradeNo("1000002");
        model.setSubject("丁浩大酒店");
        model.setStoreId("dh123");
        model.setTotalAmount("666");
        model.setBody("买他买他就买他");
        model.setQrPayMode("1");
        model.setQrcodeWidth(300L);
        AlipayTradePayRequest request=new AlipayTradePayRequest();
        AlipayTradePayResponse response=alipayClient.pageExecute(request,"post");
        if(response.isSuccess()){
            System.out.println("---------成功");
        }else {
            System.out.println("---------失败");
        }
    }
}
